<?php
namespace control;
/*
*生产不良处理类
*/

class productBadDealClass extends adIndexClass
{
    private const page = 'productBadDeal';
    private const table = 'quality_order';
    private const tableMx = 'quality_order_reason';
    private const title = '不良处理';
    private array $stateOption = ['待处理', '已处理'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => "单据编号",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'type'  => [
                        'name'  => '类型',
                        'width' => 100,
                    ],
                    'line'         => [
                        'name'  => '生产线',
                        'width' => 200,
                    ],
                    'code'          => [
                        'name'  => '物料编码',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'materialName'          => [
                        'name'  => '物料名称',
                        'width' => 150,
                    ],
                    'model'          => [
                        'name'  => '规格型号',
                        'width' => 100,
                    ],
                    'unit'          => [
                        'name'  => '单位',
                        'width' => 60,
                    ],
                    'num'          => [
                        'name'  => '不良数量',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'reason'          => [
                        'name'  => '不良原因',
                        'width' => 100,
                    ],
                    'dealMethod'          => [
                        'name'  => '处置方式',
                        'width' => 100,
                    ],
                    'checkTime'          => [
                        'name'  => '质检日期',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 100,
                    ],
                    'dealDate'          => [
                        'name'  => '处理日期',
                        'width' => 100,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "单据编号" => text(array("name" => "orderNo")),
                    "物料编码" => text(array("name" => "code")),
                    "物料名称" => text(array("name" => "materialName")),
                ],
                [
                    "不良原因" => text(array("name" => "reason")),
                    "类型" => select(["name" => "type", 'option' => ['1'=>'来料检验','2'=>'制终检验']]),
                    '处置方式' => repeatSelect(array('name' => 'method', 'sqlForm' => " quality_order_reason where coid = '" . self::$coid . "' and dealMethod !=''", 'sqlField' => 'dealMethod')),

                ],
                [
                    '生产线' => selectMultiple(["name" => "lineId", 'table' => "product_line", 'sqlId' => 'id', 'where' => "coid = '" . self::$coid . "'", 'sqlField' => 'name', 'class' => 'width200']),
                    "质检日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    "状态" => select(["name" => "state", 'option' => $this->stateOption]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        $button = "";
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "a.orderNo" => $this->post('orderNo'),
            "c.name" => $this->post('materialName'),
            "c.code" => $this->post('code'),
        );
        //全等查询数组
        $equal = array(
            "a.state" => '已质检',
            "a.type"=>$this->post('type'),
            "b.state" => $this->post('state'),
            "b.dealMethod" => $this->post('method'),
            "a.targetId" => $this->post('lineId'),
            'b.coid' => self::$coid
        );
        $and = " and a.type in (1,2)";
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'), 'date', 'checkTime');
        }
        if ($this->post('reason')){
            $and.=" and b.reasonId in (select id from quarantine_reason where coid = '".self::$coid."' and reason like '%".$this->post('reason')."%')";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'b.time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array(
            "table" => self::table . " as a join " . self::tableMx . " as b on a.id = b.orderId left join material as c on c.id = a.materialId",
            'field' => "b.*,c.code,c.model,c.name as materialName,a.materialId,a.targetId,a.orderNo,a.checkTime,a.unit,a.type",
            "where" => $where,
            "order" => $orderBy['orderBy']
        ));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $type = '';
            if ($array['type'] ==1){
                $type = '来料检验';
                if ($array['state'] =='待处理'){
                    $dominate['receive'] =  array("title" => "让步接收", "click" => "layer('" . self::page . "','operate',{id:'" . $array['id'] . "',act:'scrap'})");
                    $dominate['refund'] =  array("title" => "退货", "click" => "newIframe('采购退货单详情','" . root . "control/adIndex.html?cla=purchaseRefundOrder&fun=edit&linkId={$array['id']}&sourceId=" . $array['id'] . "')");
                }
            }elseif($array['type'] ==2){
                $type = '制终检验';
                if ($array['state'] =='待处理'){
                    $dominate['scrap'] =  array("title" => "报废", "click" => "layer('" . self::page . "','operate',{id:'" . $array['id'] . "',act:'waste'})");
//                    $dominate['scrap'] =  array("title" => "报废", "click" =>  "newIframe('其他出库单详情','" . root . "control/adIndex.html?cla=outStockOther&fun=edit&linkId={$array['id']}&sourceId=" . $array['id'] . "')");
                    $dominate['rework'] =  array("title" => "返工", "click" => "newIframe('生产计划单详情','" . root . "control/adIndex.html?cla=machiningOrder&fun=edit&linkId={$array['id']}&sourceId=" . $array['id'] . "')");
                }
            }
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'type':
                        $row[] = $type;
                        break;
                    case 'line':
                        $line = query('product_line', "id = '$array[targetId]'");
                        $row[] = $line['name'];
                        break;
                    case 'num':
                        $row[] = self::lostZero($array['num'], 'numPrecision');
                        break;
                    case 'reason':
                        $reason = query('quarantine_reason', "id = '$array[reasonId]'");
                        $row[] = $reason['reason'];
                        break;
                    case 'dealDate':
                        $row[] = self::null($array['dealDate']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => self::table . " as a join " . self::tableMx . " as b on a.id = b.orderId left join material as c on c.id = a.materialId",
            'single' => $where,
            'field'  => "ifnull(sum(b.num),0) as num",
        ]);
        $total    = [
            'num'        => self::lostZero($totalQuery['num'], 'numPrecision'),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = $page['hint'] . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 报废
     * @return bool|string
     */
    public function wasteEdit(): bool|string
    {
        $idArr = $this->post('id') ? [$this->post('id')] : $this->post('listId');
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有" . self::title . "的编辑权限";
        } elseif (empty($idArr) || !is_array($idArr)) {
            $json['warn'] = "请选择数据";
        } else {
            $field = [
                'state' => '已处理',
                'dealDate'=>$this->date,
                'dealId'=>self::$stid,
            ];
            $json['warn'] = update(array('table' => self::tableMx, 'field' => $field, 'where' => " id in ('" . implode("','", $idArr) . "') and state = '待处理' and coid = '".self::$coid."'"));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $text = $this->control['name'] . "报废了" . self::title . "， id：【" . implode(",", $idArr) . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = '处理成功';
                $json['warn'] = 2;
            }
        }
        //返回
        return json_encode($json, 320);
    }
    /**
     * 让步接收
     * @return bool|string
     */
    public function scrapEdit(): bool|string
    {
        $idArr = $this->post('id') ? [$this->post('id')] : $this->post('listId');
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有" . self::title . "的编辑权限";
        } elseif (empty($idArr) || !is_array($idArr)) {
            $json['warn'] = "请选择数据";
        } else {
            $field = [
                'state' => '已处理',
                'dealDate'=>$this->date,
                'dealId'=>self::$stid,
            ];
            $json['warn'] = update(array('table' => self::tableMx, 'field' => $field, 'where' => " id in ('" . implode("','", $idArr) . "') and state = '待处理' and coid = '".self::$coid."'"));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $text = $this->control['name'] . "让步接收了" . self::title . "， id：【" . implode(",", $idArr) . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = '处理成功';
                $json['warn'] = 2;
            }
        }
        //返回
        return json_encode($json, 320);
    }
    /**
     * 返工
     */
    public function rework(): bool|string
    {
        $linkId = $this->post('listId');
        if (empty($linkId)) {
            $html = '请选择需要返工的数据';
        } else {
            $linkIdArr = explode(',', $linkId);
            $tempId = [];
            $num = 0;
            foreach ($linkIdArr as $reasonId) {
                $qualityReason = query('quality_order_reason', "id = '$reasonId'");
                $quality = query('quality_order', "id = '$qualityReason[orderId]'");
                if (!empty($tempId) && !in_array($quality['materialId'], $tempId)) {
                    $html = '请选择相同的物料及属性';
                    break;
                } else {
                    $tempId[] = $quality['materialId'];
                    $num += $qualityReason['num'];
                }
            }
        }
        if (empty($html)) {
            //生成表单
            $html = $this->layerEdit(array("table" => array(
                array(
                    "提示：" => "是否确认返工所勾选的数据",
                ),
            ), 'hidden' => hidden(array('name' => 'sourceId', 'value' => $linkIdArr[0] ?? '')) . hidden(array('name' => 'linkId', 'value' => $linkId)) . hidden(array('name' => 'num', 'value' => $num ?? 0))
            ));
            $html .= <<<efo
<script>
function goToMachining(){
    let sourceId = $("[name='sourceId']").val();
    let linkId = $("[name='linkId']").val();
    let num = $("[name='num']").val();
    location.href=root+'control/adIndex.html?cla=machiningOrder&fun=edit&sourceId='+sourceId+'&num='+num+'&linkId='+linkId
}
</script>
efo;

        }

        //返回
        return $this->layer(array(
            "title" => "返工",
            "height" => 180,
            "html" => $html,
            'button' => "<input onclick=\"goToMachining()\" type='button' class='button' value='确认'>"
        ));
    }


    /*详情页*/
    public function detail(): string
    {
        $infoMx = query(self::tableMx, " id = '{$this->get('id')}'");
        if (empty($infoMx['id'])) {
            $html = '未找到此' . self::title;
        } else {
            //菜单
            $data = array(
                "id" => $infoMx['id'],
            );
            $info = query(self::table, "id = '$infoMx[orderId]'");

            $tr[] = ['不良原因', '不良数量', '处置方式', '备注', '状态', '处理人', '处理日期'];
            $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
            foreach ($result['array'] as $array) {
                $quarantine_reason = query('quarantine_reason', "id = '$array[reasonId]'");
                $tr[] = [
                    $quarantine_reason['reason'],
                    self::lostZero($array['num'],'numPrecision'),
                    $array['dealMethod'],
                    $array['text'],
                    $array['state'],
                    self::findStaff($array['dealId']),
                    self::null($array['dealDate']),
                ];
            }
            $total      = [
                1  => "<span id='total_num'>" . self::lostZero(array_sum(array_column((array)$result['array'],'num')),'num') . "</span>",
            ];

            $line = query('product_line', "id = '$info[targetId]'");
            $material = query('material', " id = '$info[materialId]'");
            //生成表单
            $data['html'] = $this->tableShow(array(
                "基本信息" => array(
                    array(
                        "生产部门" => $line['workshop'] . '-' . $line['name'],
                        "完工日期" => date('Y-m-d', strtotime($info['time'])),
                        "物料" => $material['model'] . '-' . $material['name'],
                        "完工数量(" . $info['unit'] . ")" => self::lostZero($info['num'],'numPrecision'),
                    ),
                    array(
                        "合格数量(" . $info['unit'] . ")" => self::lostZero($info['passNum'],'numPrecision'),
                        "不良数量(" . $info['unit'] . ")" => $info['num'] - $info['passNum'],
                        "单据编号" => $info['orderNo'],
                        "质检人" => self::findStaff($info['checkId']),
                    ),
                    array(
                        "状态" => $info['state'] . self::operateLog($info['id'])
                    ),
                )
            ));
            $data['html'] .= $this->detailList([
                'title' => '不良明细',
                'html' => $this->listTable(array('tr' => $tr, 'showSort' => true, 'total' => $total)),
            ]);
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }


    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = $word = false; // 需要密码
        $form = $power = '';
        switch ($act) {
            case 'scrap':
                $act = 'edit';
                $msg = '让步';
                $title = '是否让步接收所选的数据？';
                $function = 'scrapEdit';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                $word = true;
                break;
            case 'waste':
                $act = 'edit';
                $msg = '报废';
                $title = '是否报废所选的数据？';
                $function = 'wasteEdit';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                $word = true;
                break;
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm, quoForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word' => $word
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] == '已确认') {
                    $warn = "删除失败：已确认，暂不能删除";
                } else {
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    delete(array("table" => self::tableMx, "where" => " orderId = '$id' "));
                    delete(array("table" => "auditing_follow", "where" => " typeId = '$id' "));
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    /**
     * 打印
     */
    public function printPage(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        $companyName = para('companyName');//公司名称
        $line = query('product_line', "id = '$info[lineId]'");
        $goodsHtml = '';
        //二维码
        $url = root . 'pay/wxpay/wxScanPng.php?url=' . urlencode("source=purchase_order&id=" . $info['id']);
        $infoMx = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list asc"));
        $totalNum = $totalMoney = 0;
        foreach ($infoMx['array'] as $index => $array) {
            $material = query('material', "id = '$array[materialId]'");
            $totalNum += $array['num'];
            $goodsHtml .= "
                             <tr class='have_border'>
                               <td>" . ($index + 1) . "</td>
                               <td>{$material['code']}</td>
                               <td>{$material['name']}</td>
                               <td>{$material['model']}</td>
                               <td>{$material['unit']}</td>
                               <td>".self::lostZero($array['quantity'],'numPrecision')."</td>
                               <td>{$array['text']}</td>
                             </tr>
                            ";
        }
        $info['startDate'] = date('Y/m/d', strtotime($info['startDate']));
        $info['endDate'] = date('Y/m/d', strtotime($info['endDate']));
        $material = query('material', "id = '$info[materialId]'");
        $saleOrder = query('sale_order', "id = '$info[sourceId]'");
        $divHtml = "
                 <div>
                      <div class='printTitle' style='font-weight: bold'>{$companyName}</div>
                      <div class='printSubTitle'>生产加工(返工)单</div>
                 </div>
                 <div class='table-top-title'>
                     <ul>
                         <li>生产部门：{$line['name']}</li>
                         <li>计划开工：{$info['startDate']}</li>
                         <li>计划完工：{$info['endDate']}</li>
                         <li>生产计划单号：{$info['orderNo']}</li>
                         <li>物料：{$material['name']}</li>
                         <li>规格型号：{$material['model']}</li>
                         <li>数量：".self::lostZero($info['num'],'numPrecision')."</li>
                         <li>销售订单：{$saleOrder['orderNo']}</li>
                         <li>备注：{$info['text']}</li>
                     </ul>
                 </div>
              <table class='printTable'  data-op-type='block-box'>
                <tbody class='nop-fill-box'>
               <tr class='have_border'>
                   <td>序号</td>
                   <td>物料编码</td>
                   <td>物料名称</td>
                   <td>规格型号</td>
                   <td>单位</td>
                   <td>数量</td>
                   <td>备注</td>
                </tr>
                {$goodsHtml}
                 <tr class='have_border'>
                    <td>合计</td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td>{$totalNum}</td>
                    <td></td>
                </tr>

                 <tr class='have_border'>
                    <td colspan='13'>
                         <div>
                               <img alt='二维码' style='width: 100px;vertical-align: top' src='$url'>
                               <div class='footer-ul-parent'>
                               <ul class='footer-ul'>
                                   <li>打印时间：" . date('Y/m/d H:i') . "</li>
                                   <li>制单人：" . self::findStaff($info['stid']) . "</li>
                                   <li></li>
                               </ul>
                               </div>
                         </div>
                    </td>
                </tr>
               </tbody>
              </table>
            ";
        $html = <<<eof
                    <div id="content-box" style="display: none">
                        <div data-op-type='new-page'></div>
                    <!--    <div data-op-type="pendants">&lt;!&ndash; 定义页面部件（页眉/页脚/书签/水印背景等） &ndash;&gt;-->
                    <!--        <div class='pendant-title'>实发工资表</div>-->
                    <!--    </div>-->
                       {$divHtml}
                    </div>
                  <style>
                   .footer-ul-parent{float: right;margin-right: 10px}
                  .footer-ul li{margin-top: 10px}
                  .table-top-title{
                    height: 30px;
                    line-height: 30px;
                    font-size: 14px;
                    margin-top: 20px;
                  }
                  .table-top-title>ul>li{float: left;width: 250px;}
</style>
eof;
        $print = new printClass();

        return $print->showPrint($html, 'landscape');
    }
}

